package com.xplan.actions;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.Result;
import com.xplan.util.JsonUtils;

/**
 * 包含 Ajax 请求处理结果的通用结构。该结构包含
 * {@link #success}, {@link #message}, {@link #data} 三个属性。
 *
 */
public class JsonResult implements Result {

    public static final JsonResult SUCCESS = new JsonResult();

    public static JsonResult success(String message) {
        return new JsonResult(true, message);
    }

    public static JsonResult fail(String message) {
        return new JsonResult(false, message);
    }

    //////////////////////////////////////////////

    /**
     * 请求是否成功处理
     */
    private boolean success = true;

    /**
     * 处理成功或失败时的相关信息
     */
    private String message = null;

    /**
     * 返回值
     */
    private Map<String, Object> data = new HashMap<String, Object>();

    public JsonResult() {
    }

    public JsonResult(Map<String, Object> data) {
        this.data = data;
    }

    public JsonResult(boolean success, String message) {
        this.message = message;
        this.success = success;
    }

    public JsonResult(final String name, final Object value) {
        Map<String, Object> data = new HashMap<String, Object>();
        data.put(name, value);
        this.data = data;
    }

    public boolean isSuccess() {
        return success;
    }

    public JsonResult setSuccess(boolean success) {
        this.success = success;
        return this;
    }

    public String getMessage() {
        return message;
    }

    public JsonResult setMessage(String message) {
        this.message = message;
        return this;
    }

    public Map<String, Object> getData() {
        return data;
    }

    /////////////////////////////////////////

    public JsonResult put(String name, Object value) {
        data.put(name, value);
        return this;
    }

    public Object get(String name) {
        return data.get(name);
    }

    public void execute(ActionInvocation actionInvocation) throws Exception {
        HttpServletResponse response = ServletActionContext.getResponse();
        response.setContentType("application/json");

        PrintWriter writer = response.getWriter();
        writer.write(this.toString());
        writer.flush();
    }

    @Override
    public String toString() {
        return "{" +
                "success=" + success +
                ", message='" + message + '\'' +
                ", data=" + JsonUtils.map2json(data) +
                '}';
    }
}
